import Vue from 'vue'

// 时间格式化
export function formatDate (date, fmt) {
	if (/(y+)/.test(fmt)) {
		fmt = fmt.replace(RegExp.$1, (date.getFullYear()+'').substr(4-RegExp.$1.length))
	}
	let o = {
		'M+': date.getMonth() + 1,
		'd+': date.getDate(),
		'h+': date.getHours(),
		'm+': date.getMinutes(),
		's+': date.getSeconds()
	}
	for (let k in o) {
		if (new RegExp(`(${k})`).test(fmt)) {
			let str = o[k] + ''
			fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1 ? str : addZero(str)))
		}
	}
	return fmt
}

function addZero (str) {
	return ('00' + str).substr(str.length)
}

function padding (str) {
	if (str < 10) {
		str = '0' + str
	}
	return str
}
export function getUrlParms(name) {
  return decodeURIComponent((new RegExp('[?|&]'+name+'='+'([^&;]+?)(&|#|;|$)').exec(location.href)||[,""])[1].replace(/\+/g,'%20'))||null;
}

// 秒杀
export function getNowTime () {
	let result = []
  let d = new Date();
  let year = d.getFullYear()
  let month = d.getMonth() + 1
  let day = d.getDate() 
  let hours = d.getHours()
  if (hours%2 != 0) {
    hours -= 1
  }
  let now = year +'-'+ padding(month) +'-'+ padding(day)+' '+ hours +':00'+ ':00'
  for (let i = 0; i < 6; i++) {
    let time_stamp = Date.parse(now) + i * 3600000 * 2
    let time = new Date(time_stamp)
    let t_hours = time.getHours()
    result.push({ 'hours': padding(t_hours), 'text': '即将开场', 'date': time_stamp}) 
    result[0].text = '秒杀中'
  }
  return result
}

// 数组去重
export function unique (array) {
	let result = []
	for (let i = 0; i<array.length; i++) {
		if (result.indexOf(array[i]) == -1) {
			result.push(array[i])
		}
	}
	return result
}

// 小数相乘bug
export function accMul(arg1, arg2) {
	var m = 0, s1 = arg1.toString(), s2 = arg2.toString()
	try { m += s1.split(".")[1].length } catch (e) { }
	try { m += s2.split(".")[1].length } catch (e) { }
	return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m)
}

// 保留数字两位小数点
export function toDecimal(x) { 
  var f = parseFloat(x); 
  if (isNaN(f)) { 
    return false; 
  } 
  var f = Math.round(x*100)/100; 
  var s = f.toString(); 
  var rs = s.indexOf('.'); 
  if (rs < 0) { 
    rs = s.length; 
    s += '.'; 
  } 
  while (s.length <= rs + 2) { 
    s += '0'; 
  } 
  return s; 
} 

// 存储localStorage
export const setStore = (name, content) => {
	if (!name) return;
	if (typeof content !== 'string') {
		content = JSON.stringify(content);
	}
	window.localStorage.setItem(name, content);
}

// 获取localStorage
export const getStore = name => {
	if (!name) return;
	return window.localStorage.getItem(name);
}

//  删除localStorage
export const removeStore = name => {
	if (!name) return;
	window.localStorage.removeItem(name);
}